package com.test.flink_introduction;

import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * lambda 表达式改写统计单词个数例子
 */
public class F01Demo02 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment see = null;
        see = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> dss = see.socketTextStream("127.0.0.1", 8899);
//            SingleOutputStreamOperator<String> res = dss.map(String::toUpperCase);
//        SingleOutputStreamOperator<String> res = dss.flatMap((String line, Collector<String> out) -> {
//            String[] words = line.split("\\s+");
//            for (String word : words) {
//                out.collect(word);
//            }
//        }).returns(new TypeHint<String>() {});
//        SingleOutputStreamOperator<String> res = dss.flatMap((String line, Collector<String> out) -> {
//            String[] words = line.split("\\s+");
//            for (String word : words) {
//                out.collect(word);
//            }
//        }, StringDataTypeInfo.of(String.class));

        SingleOutputStreamOperator<Tuple2<String, Integer>> res = dss.flatMap((String line, Collector<Tuple2<String, Integer>> out) -> {
            String[] words = line.split("\\s+");
            for (String word : words) {
                out.collect(Tuple2.of(word, 1));
            }
        }).returns(new TypeHint<Tuple2<String, Integer>>() {
        });

        res = res.keyBy(tp -> tp.f0).sum(1);

        res.print();
        see.execute();

    }
}
